package org.formatter.rule;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleTextRule implements Rule {
	private String beforechip;
	private String chip;
	private String replacechip;
	private String afterchip;

	public String getBeforechip() {
		return beforechip;
	}

	public void setBeforechip(String beforechip) {
		this.beforechip = beforechip;
	}

	public String getChip() {
		return chip;
	}

	public void setChip(String chip) {
		this.chip = chip;
	}

	public String getReplacechip() {
		return replacechip;
	}

	public void setReplacechip(String replacechip) {
		this.replacechip = replacechip;
	}

	public String getAfterchip() {
		return afterchip;
	}

	public void setAfterchip(String afterchip) {
		this.afterchip = afterchip;
	}

	public String format(String original) {
		if (null != chip) {
			StringBuffer formattedStr = new StringBuffer();

			Matcher m = Pattern.compile(Pattern.quote(chip)).matcher(original);
			int index = 0;
			while (m.find()) {
				String block = original.substring(index, m.start());
				formattedStr.append(block);
				beforechip(formattedStr);
				replacechip(formattedStr);
				afterchip(formattedStr);
				index = m.end();
			}
			formattedStr.append(original.substring(index));
			return formattedStr.toString();
		} else {
			return original;
		}
	}

	private void afterchip(StringBuffer formattedStr) {
		if (null != afterchip) {
			formattedStr.append(afterchip);
		}
	}

	private void replacechip(StringBuffer formattedStr) {
		if (null != replacechip) {
			formattedStr.append(replacechip);
		} else {
			formattedStr.append(chip);
		}
	}

	private void beforechip(StringBuffer formattedStr) {
		if (null != beforechip) {
			formattedStr.append(beforechip);
		}
	}
}
